package com.qc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.qc.enity.Goods;
import com.qc.enity.User;
import com.qc.mapper.GoodsMapper;
import com.qc.mapper.UserMapper;
import com.qc.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 冰箱物品业务层
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public IPage<Goods> goodsList(String oid, Page page) {
        //python yolo

        //根据userId分页查询
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getBid, oid);
        IPage data = goodsMapper.selectPage(page, queryWrapper);

        return data;
    }

    @Override
    public IPage<Goods> goodsSelect(String oid, Page page, String name) {

        //根据userId进行模糊查询
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();

        IPage data = goodsMapper.selectPage(page, queryWrapper);

        return data;
    }


    @Override
    public Integer addGoods(String oid, String name, Integer num, String goodsDescribe, Date expiration, String unit, String type ,String photoUrl) {


        MPJLambdaWrapper<User> wrapper = new MPJLambdaWrapper<User>()
                .select(User::getUserId)
                .eq(User::getOid, oid);
        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users.get(0).getUserId());
        //连表查询，返回dish对象
        Integer userId = users.get(0).getUserId();
//        手动生成随机goodsId
        System.out.println("userID***" + userId);
        String goodsId = UUID.randomUUID().toString();
        Goods goods = new Goods();
//        goods.setBid(userId);
        goods.setOid(oid);
        goods.setGoodsId(goodsId);
        goods.setGoodsDescribe(goodsDescribe);
        goods.setGoodsName(name);
        goods.setType(type);
        goods.setUnit(unit);
        goods.setExpirationDate(expiration);
        Date date = new Date();
        goods.setCreatDate(date);
        goods.setGoodsNumber(num);
        goods.setPhotoUrl(photoUrl);
        System.out.println(goods);
        int rows = goodsMapper.insert(goods);
        System.out.println(rows);
        return rows;
    }

    @Override
    public Integer removeGoods(String oid, String goodsId, Integer num) {
        //根据oid获取该用户所使用的冰箱id(userId)
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOid, oid);
        User user = userMapper.selectOne(queryWrapper);
        Integer userId = user.getUserId();

        //根据oid添加食材信息
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getBid, userId).eq(Goods::getGoodsId, goodsId).eq(Goods::getOid, oid);

        //获取当前物品数量
        LambdaQueryWrapper<Goods> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Goods::getBid, userId).eq(Goods::getGoodsId, goodsId).eq(Goods::getOid, oid);
        Goods goods1 = goodsMapper.selectOne(queryWrapper1);
        Integer goodsNumber = goods1.getGoodsNumber();

        //计算删除后剩余物品数量
        Integer resultNum = goodsNumber - goodsNumber * num / 4;

        Goods goods = new Goods();
        goods.setGoodsNumber(resultNum);
        int rows = goodsMapper.update(goods, updateWrapper);

        return rows;
    }

    @Override
    public int addGoodsByYoLo(String userId) {
        try {
            // 创建进程执行命令，激活虚拟环境并运行Python脚本
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "bash", "-c", "python /Users/dealthknight/Downloads/yolov5-master/detect.py " + "--bid "+ userId
            );
            processBuilder.inheritIO(); // 继承IO流，这样就能直接打印输出到控制台

            // 启动进程
            Process process = processBuilder.start();

            // 创建一个 BufferedReader 来读取进程的标准输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            // 用于存储输出内容的 StringBuilder
            StringBuilder ans = new StringBuilder();
            String line;

            // 逐行读取输出，并添加到 StringBuilder 中
            while ((line = reader.readLine()) != null) {
                ans.append(line).append("\n");
            }
            Thread.sleep(10000);
            // 停止 Python 程序
            process.destroy(); // 尝试正常终止进程
            if (process.isAlive()) {
                process.destroyForcibly(); // 如果进程仍在运行，强制终止
            }
            // 等待进程结束
            System.out.println(ans);
            int exitCode = process.waitFor();

            System.out.println("Command executed with exit code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return 0;
    }

}
